package service

import (
	"errors"
	"gorm.io/gorm"
	"shop-bean/constant"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/loggerV2"
	"shop-common/library/variables"
	"shop-common/utils"
	"strconv"
	"strings"
)

type IStoreProductService interface {
	Create(request *request.StoreProductRequest) error
	FindAttr()
	CheckActivity(id uint) (bool, error)
}

type StoreProductService struct {
	db *gorm.DB
}

func NewStoreProductService() IStoreProductService {
	return &StoreProductService{variables.GormDB()}
}

func (s *StoreProductService) Create(request *request.StoreProductRequest) error {
	if !request.SpecType {
		if len(request.AttrValue) > 0 {
			return errors.New("单规格商品属性值不能大于1")
		}
	}

	var storeProduct *model.StoreProduct
	err := utils.StructMapStrict(request, &storeProduct)
	if err != nil {
		loggerV2.Errorf("request copy model.StoreProduct failed: err %v", err)
		return errors.New("请求参数不正确")
	}

	storeProduct.IsShow = false

	// 设置Acticity活动
	storeProduct.Activity = getProductActivityStr(request.Activity)

	//主图
	return nil
}

/**
 * 商品活动字符串
 * @param activityList 活动数组
 * @return 商品活动字符串
 */
func getProductActivityStr(activityList []string) string {
	if len(activityList) == 0 {
		return "0, 1, 2, 3"
	}

	var activities = make([]string, 0)
	for _, activity := range activityList {
		switch activity {
		case constant.PRODUCT_TYPE_NORMAL_STR:
			activities = append(activities, strconv.Itoa(constant.PRODUCT_TYPE_NORMAL))
		case constant.PRODUCT_TYPE_SECKILL_STR:
			activities = append(activities, strconv.Itoa(constant.PRODUCT_TYPE_SECKILL))
		case constant.PRODUCT_TYPE_BARGAIN_STR:
			activities = append(activities, strconv.Itoa(constant.PRODUCT_TYPE_BARGAIN))
		case constant.PRODUCT_TYPE_PINGTUAN_STR:
			activities = append(activities, strconv.Itoa(constant.PRODUCT_TYPE_PINGTUAN))
		}
	}

	return strings.Join(activities, ",")
}

//获取商品规格
func (s *StoreProductService) FindAttr() {

}

//检查商品是否有活动
func (s *StoreProductService) CheckActivity(id uint) (bool, error) {
	//todo 商品参与秒杀活动开启，无法进行此操作 storeSeckillService
	//todo 商品参与砍价活动开启，无法进行此操作 storeBargainService
	//todo 商品参与拼团活动开启，无法进行此操作 storeCombinationService
	return true, nil
}
